using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.IO;
using Android.Content.Res;
using Android.Util;
using Microsoft.Xna.Framework;

namespace SharpieAndroid
{
    static class Config
    {
        public static Dictionary<string, string> Nodes = new Dictionary<string, string>();
        public static readonly string FileName = "sharpie.cfg";
        public static readonly string FilePath = Path.Combine(Activity1.AppDataPath, FileName);

        public static bool Load(out string error)
        {
            try
            {
                Nodes.Clear();
                using (StreamReader sr = File.OpenText(FilePath))
                {
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();
                        if (!line.Trim(new char[] { ' ' }).StartsWith("#") & line.Length > 3)
                        {
                            string[] confignode = { line.Substring(0, line.IndexOf('=')), line.Remove(0, line.IndexOf('=') + 1) };
                            Nodes.Add(confignode[0], confignode[1]);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return false;
            }

            error = "";
            return true;
        }

        public static bool Save(out string error)
        {
            try
            {
                using (StreamWriter sw = File.CreateText(FilePath))
                {
                    sw.WriteLine("# Sharpie Android Game Configuration\n# Bad configuration may result in inability to start a game or errors while running!\n");

                    foreach (KeyValuePair<string, string> entry in Nodes)
                    {
                        sw.WriteLine("{0}={1}", entry.Key, entry.Value);
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return false;
            }

            error = "";
            return true;
        }

        public static void RestoreDefault(AssetManager assets)
        {
            using (StreamReader sr = new StreamReader(assets.Open("sharpie.cfg")))
            {
                using (StreamWriter sw = File.CreateText(Config.FilePath))
                {
                    while (!sr.EndOfStream) sw.WriteLine(sr.ReadLine());
                }
            }
        }
    }
}